<template>
    <div class="container" id="__material__">
        1111111111122222222
      <!-- v-if="status !== 'edit'" -->
      <div style="margin: 10px 0">
        <!-- <el-button
          size="mini"
          type="primary"
          @click="dialogVisible = true"
          icon="el-icon-plus"
          v-if="hasEditRight || status !== 'edit'"
          >新增</el-button
        > -->
        <el-button
          size="mini"
          type="primary"
          @click="onAddData"
          icon="el-icon-plus"
          v-if="hasEditRight || status !== 'edit'"
          >新增</el-button
        >
      </div>
      <div>
        <el-table
          :show-header="showHeader"
          border
          size="small"
          :data="source"
          v-loading="loading"
          style="width: 100%"
          @cell-dblclick="handleCellEdit"
          ref="table"
        >
          <!-- <el-table-column
            prop="id"
            width="50"
            label="序号"
            align="center"
          ></el-table-column> -->
          <el-table-column
            v-for="(column, index) in columns"
            :key="column.prop"
            :prop="column.prop"
            :fixed="column.fixed"
            :label="column.label"
            :align="column.align"
            :show-overflow-tooltip="true"
            :min-width="column.minWidth"
          >
            <template slot-scope="scope">
              <div v-if="column.prop == 'option'">
                <el-button
                  v-if="!scope.row['editing'] && hasEditRight"
                  @click="toEdit(scope)"
                  type="text"
                  >编辑</el-button
                >
                <el-button
                  v-if="scope.row['editing']"
                  @click="toSave(scope)"
                  type="text"
                  >保存</el-button
                >
                <el-button
                  v-if="scope.row['editing']"
                  @click="toCancel(scope)"
                  type="text"
                  >取消</el-button
                >
                <el-button
                  @click="toDelete(scope)"
                  type="text"
                  v-if="status !== 'edit'"
                  >删除</el-button
                >
                <el-button
                  v-if="hasEditRight && status !== 'edit'"
                  @click="moveUp(scope)"
                  type="text"
                  >上移</el-button
                >
                <!-- <el-select
                  style="width: 68px; margin: 0 10px"
                  filterable
                  v-model="targetI"
                  v-if="hasEditRight || status !== 'edit'"
                  size="small"
                  @change="moveToTarget(scope)"
                >
             
  
                  <el-option
                    v-for="item in enumOption"
                    :label="item.label"
                    :key="item.value"
                    :value="item.value"
                  />
                </el-select> -->
                <el-button
                  v-if="hasEditRight && status !== 'edit'"
                  @click="moveDown(scope)"
                  type="text"
                  >下移</el-button
                >
              </div>
              <div v-else>
                <div v-if="column.canEdit && scope.row['editing']">
                  <!-- 编辑数据部分 -->
                  <input
                    class="inner-input"
                    :id="column.prop + index"
                    @input="(e) => (scope.row[column.prop] = e.target.value)"
                    :value="scope.row[column.prop]"
                  />
                </div>
                <span v-else>{{ scope.row[column.prop] }}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container" v-if="showPage && total">
          <!-- <el-pagination
            class="mt20 fr"
            @current-change="changePage"
            @size-change="handleSizeChange"
            :current-page="current"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination> -->
        </div>
      </div>
  
      <!-- 新增数据弹窗 -->
      <el-dialog title="新增数据" :visible.sync="dialogVisible" width="440px" style="z-index: 9999;margin-top:200px;">
        <el-form
          :inline="true"
          ref="addForm"
          :rules="modelRules"
          :model="addForm"
          size="mini"
          class="demo-form-inline"
        >
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item
                prop="columnName"
                label="费用项名称"
                label-width="120px"
              >
                <el-select
                  v-model="addForm.columnName"
                  @change="handleColumnchange"
                  placeholder="请输入字段名"
                  :remote-method="showChoice"
                  filterable
                  :allow-create="true"
                  remote
                  size="small"
                >
                  <el-option
                    v-for="(item, i) in options"
                    :key="i"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="type" label="费用项编码" label-width="120px">
                <!-- <el-select
                  v-model="addForm.type"
                  placeholder="请选择字段类型"
                  size="small"
                >
                  <el-option
                    v-for="(item, index) in typeOptions"
                    :key="index"
                    :label="item.name"
                    :value="item.code"
                    >{{ item.name }}</el-option
                  >
                </el-select> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="notes" label="付款金额（元）" label-width="120px">
                <el-input
                  v-model="addForm.notes"
                  placeholder="请输入注释"
                  size="small"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="notes" label="金额大写" label-width="120px">
                <el-input
                  v-model="addForm.notes"
                  placeholder="请输入注释"
                  size="small"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="notes" label="费用项说明" label-width="120px">
                <el-input
                  v-model="addForm.notes"
                  placeholder="请输入注释"
                  size="small"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="notes" label="备注" label-width="120px">
                <el-input
                  v-model="addForm.notes"
                  placeholder="请输入注释"
                  size="small"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="dialogVisible = false">
            取 消
          </el-button>
          <el-button size="mini" type="primary" @click="onAddData">
            提交
          </el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import Sortable from "sortablejs";
//   import {
//     fetchColumnTypeOptions,
//     addTableNameColumn,
//     editTableNameColumn,
//     fetchOptions,
//   } from "@/api/createTable/common.js";
  export default {
    props: {
      source: {
        type: Array,
        default: [],
      },
      dbType: {
        type: String,
        default: "hive",
      },
      status: {
        type: String,
        default: "",
      },
      tableName: {
        type: String,
        default: "",
      },
      dbName: {
        type: String,
        default: "",
      },
      businessOwner: {
        type: String,
        default: "",
      },
      dataOwner: {
        type: String,
        default: "",
      },
    },
    computed: {
      hasEditRight() {
        let user = this.$store.state.user.name;
        if (
          this.businessOwner === user ||
          this.dataOwner === user ||
          this.$store.state.user.isSupAdm === true
        ) {
          return true;
        } else {
          return false;
        }
      },
      enumOption() {
        let arr = [];
        for (let i = 0; i < this.source.length; i++) {
          arr.push({
            label: i + 1,
            value: i,
          });
        }
        return arr;
      },
    },
    data() {
      return {
        targetI: "",
        columns: [
          {
            prop: "columnName",
            label: "费用项名称",
            align: "center",
            canEdit: this.status !== "edit" ? true : false,
            minWidth: "120",
          },
          {
            prop: "type",
            label: "费用项编码",
            align: "center",
            minWidth: "120",
          },
          {
            prop: "notes",
            label: "付款金额（元）",
            align: "center",
            canEdit: true,
            minWidth: "120",
        },
        {
            prop: "notes",
            label: "金额大写",
            align: "center",
            canEdit: true,
            minWidth: "120",
        },
        {
            prop: "notes",
            label: "费用项说明",
            align: "center",
            canEdit: true,
            minWidth: "120",
              },
              {
            prop: "notes",
            label: "备注",
            align: "center",
            canEdit: true,
            minWidth: "120",
          },
          {
            prop: "option",
            label: "操作",
            align: "center",
            fixed: "right",
            minWidth: "120",
          },
        ],
        modelRules: {
          columnName: [
            { required: true, message: "请输入字段名", trigger: "blur" },
          ],
          type: [
            { required: true, message: "请选择字段类型", trigger: "change" },
          ],
          notes: [{ required: true, message: "请输入注释", trigger: "blur" }],
        },
        typeOptions: [], //字段类型选项
        formModel: {
          user: "",
          region: "",
        },
        //新增数据
        addForm: {
          columnName: "",
          type: "STRING",
          notes: "",
        },
        // columns: data.columns,
        // source: data.source,
        editProp: "",
        total: 100,
        size: "small",
        loading: false,
        current: 1,
        pageSize: 10,
        showPage: true,
        showHeader: true,
        dialogVisible: false,
        deleteSections: [],
        options: [],
        optionData: [],
      };
    },
    watch: {
      source: {
        deep: true,
        handler(val) {
          // val.forEach((item, index) => {
          //   item.id = index;
          // });
        },
      },
      total(val) {
        console.log(val >= this.data.length);
      },
    },
    mounted() {
      this.fetchColumnTypeOptions();
      this.dragSort();
    },
    methods: {
      handleColumnchange(value) {
        this.optionData.columnList.forEach((item, index) => {
          if (item === value) {
            this.addForm.notes = this.optionData.comment[index];
          }
        });
      },
      moveUp({ $index }) {
        if ($index === 0) {
          this.$message.warning("已经是第一个指标, 不能向上移了！");
          return;
        }
        this.source.splice($index, 0, ...this.source.splice($index - 1, 1));
      },
      moveDown({ $index }) {
        if ($index === this.source.length - 1) {
          this.$message.warning("已经是最后一个指标, 不能向下移了！");
          return;
        }
        this.source.splice($index + 1, 0, ...this.source.splice($index, 1));
      },
      dragSort() {
        const tbody = document.querySelector(".el-table__body-wrapper tbody");
        const _this = this;
        Sortable.create(tbody, {
          onEnd({ newIndex, oldIndex }) {
            const currRow = _this.source.splice(oldIndex, 1)[0];
            _this.source.splice(newIndex - 1, 0, currRow);
          },
        });
      },
      async showChoice(value) {
        //获取联想建议
        let data = await fetchOptions(value);
        this.optionData = data;
        this.options = [];
        data.columnList.forEach((item, index) => {
          this.options.push({
            name: `${item}(${data.comment[index]})`,
            code: item,
          });
        });
      },
      async fetchColumnTypeOptions() {
        // let data = await fetchColumnTypeOptions(this.dbType);
        // data.forEach((item, index) => {
        //   this.typeOptions.push({
        //     name: item,
        //     code: item,
        //   });
        // });
      },
      onAddData() {
        // this.$refs["addForm"].validate((valid) => {
        //   if (valid) {
        this.source.push({
            editing: false,
            columnName: this.addForm.columnName,
            type: this.addForm.type,
            notes: this.addForm.notes,
        });
            // if (this.status === "edit") {
            //   // 接口提交
            //   let data = {
            //     dbType: "HIVE",
            //     dbName: this.$route.query.dbName,
            //     tableName: this.$route.query.tableName,
            //     columnName: this.addForm.columnName,
            //     type: this.addForm.type,
            //     notes: this.addForm.notes,
            //     operator: this.$store.state.user.namecn,
            //     email: this.$store.state.user.name,
            //   };
            //   addTableNameColumn(data).then((res) => {
            //     if (res) {
            //       this.$message.success("新增数据成功");
            //     }
            //   });
            // }
            // this.dialogVisible = false;
            //清空上一组数据
            // this.addForm.columnName = "";
            // this.addForm.notes = "";
            // this.addForm.type = "STRING";
            // this.options = [];
        //   } 
        //   else {
        //     this.$message.closeAll();
        //     this.$message.warning("校验未通过，请检查您填写的内容");
        //     return false;
        //   }
        // });
      },
      toEdit({ row, $index }) {
        this.tempData = JSON.stringify(row);
        this.$set(this.source[$index], "editing", true);
      },
      toCancel({ $index }) {
        this.$set(this.source, $index, JSON.parse(this.tempData));
        this.$set(this.source[$index], "editing", false);
      },
      toSave({ $index }) {
        if (this.source[$index].columnName && this.source[$index].notes) {
          this.$set(this.source[$index], "editing", false);
          // 若为编辑状态，调用修改接口
          if (this.status === "edit" && this.$route.query.formtype !== "copy") {
            // 接口提交
            let data = {
              dbType: "HIVE",
              dbName: this.$route.query.dbName,
              tableName: this.$route.query.tableName,
              columnName: this.source[$index].columnName,
              type: this.source[$index].type,
              notes: this.source[$index].notes,
              operator: this.$store.state.user.namecn,
              email: this.$store.state.user.name,
            };
            editTableNameColumn(data)
              .then((res) => {
                console.log(res, 666666);
                if (res) {
                  this.$message.success("编辑成功");
                }
              })
              .catch((err) => {
                if (err) {
                  this.$message.success("本次编辑无效");
                  window.location.reload();
                }
              });
          }
        } else {
          this.$message.closeAll();
          this.$message.warning("保存失败，均为必填项");
        }
      },
      toDelete({ $index }) {
        this.source.splice($index, 1);
      },
      handleCellEdit(row, column, cell, event) {
        console.log(row, column, cell, event);
      },
    },
  };
  </script>
  <style lang="scss" scoped>
.container {
  padding: 20px 20px;
}

.pagination-container {
  overflow: hidden;
  text-align: right;
  padding: 10px 0;
}

.inner-input {
  border: 1px solid #ccc;
  border-radius: 4px;
  height: 24px;
  padding: 0 10px;
  line-height: 24px;
  color: #666;
}
</style>
  